package com.icecloud.cloud.upms.conf.security;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.logout.LogoutHandler;
import org.springframework.util.Assert;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.icecloud.cloud.upms.common.utils.RestfulResponseBody;

/**
* @author penghaozhong 
* E-mail:penghaozhong@163.com
* @version 2016年8月8日 下午9:25:22
* 
*/
public class RestLogoutHandler implements LogoutHandler {
	
	protected final Log logger = LogFactory.getLog(this.getClass());
	
	private boolean invalidateHttpSession = true;
	private boolean clearAuthentication = true;

	@Override
	public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
		Assert.notNull(request, "HttpServletRequest required");
		if (invalidateHttpSession) {
			HttpSession session = request.getSession(false);
			if (session != null) {
				logger.debug("Invalidating session: " + session.getId());
				session.invalidate();
			}
		}

		if (clearAuthentication) {
			SecurityContext context = SecurityContextHolder.getContext();
			context.setAuthentication(null);
		}

		SecurityContextHolder.clearContext();
		
		RestfulResponseBody body = new RestfulResponseBody();
		body.setReason("退出成功");
		body.setResultFlag(1);
		
		PrintWriter writer;  
        response.setStatus(200);  
		try {
			writer = response.getWriter();
			writer.write(new ObjectMapper().writeValueAsString(body));
			writer.flush();
			writer.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
